import os
import time
import win32com.client as win32
from win32com.client import constants
import pythoncom
from ..app.configs import AppConfig


def open_word(file: str, text: str) -> bool:
    # pythoncom.CoInitialize()
    print("正在搜索", text)
    software = AppConfig().docx_default_software.lower()
    if software == "word":
        word_app = win32.gencache.EnsureDispatch("Word.Application")
    elif software == "wps":
        word_app = win32.gencache.EnsureDispatch("kwps.Application")
    else:
        raise ValueError(
            f"Not support this kind of software {software} to open doc(x) file"
        )
    # 设置Word应用可见
    word_app.Visible = True

    if os.path.exists(file):
        doc = word_app.Documents.Open(file)
    else:
        raise FileNotFoundError(file)
    print(type(word_app.ActiveWindow))
    search_range = doc.Content
    find = search_range.Find
    find.IgnorePunct = True
    find.IgnoreSpace = True
    find.Execute(FindText=text)
    search_range.Select()  # 这一步必须要有，否则获取的页码不对
    word_app.Activate()
    # rng = word_app.Selection.Range
    # print('所在页：',rng.Information(constants.wdActiveEndPageNumber))
    # print('所在页：',rng.Information(constants.wdActiveEndAdjustedPageNumber))
